from PyQt6.QtCore import QObject, pyqtSignal, QThread, QTimer
from PyQt6.QtGui import QIcon, QPainter, QPixmap
from PyQt6.QtWidgets import QMainWindow, QFileDialog, QGroupBox, QMessageBox, QToolButton, QProgressBar
from PyQt6 import QtGui, QtCore, uic

from back.inclinedShaft.main import inclinedShaftDiagram
from utils.error import getError, getError2
from utils.index import resource_path
from front.components.progress import Window as Progress
from front.components.historyInclinedShaft import Window as historyInclinedShaft
from front.actions.setting import update_setting
from front.actions.showImage import show_image
from front.actions.history import get_history, setHistory


# 需要注意窗口使用的是Widget还是QMainWidget类
def select_file(lineEdit, fileType="(*)"):
    fd: QFileDialog = QFileDialog()
    fd.setNameFilter(fileType)  # 设置只选择图片文件
    if fd.exec():  # 执行
        lineEdit.setText(fd.selectedFiles()[0])


# 获取单选按钮的值
def get_radio_value(selected_button, isDraw=False):
    if isDraw:
        if selected_button.text() == "是":
            return 1  # 画线
        else:
            return 0
    else:
        if selected_button.text() == "是":
            return 0  # 做负极性，做增益
        else:
            return 1


# 创建线程安全的进度条包装器，用于跨线程传递进度更新
class ProgressBarWrapper(QObject):
    update_progress = pyqtSignal(int)  # 进度更新信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_progress_bar)
        self.timer.start(600)  # 每600毫秒更新一次进度条，60s左右走完进度条

    def update_progress_bar(self):
        current_value = self.progress_bar.value()
        if current_value >= 100:
            self.timer.stop()
        else:
            self.progress_bar.setValue(current_value + 1)
            self.update_progress.emit(current_value + 1)

    def setValue(self, value):
        self.update_progress.emit(value)  # 将值通过信号发送


# 工作线程类
class WorkerThread(QThread):
    # 新增错误信号，携带异常信息字典
    error_occurred = pyqtSignal(dict)
    finished_success = pyqtSignal()  # 成功完成信号

    def __init__(self, params, progress_wrapper):
        super().__init__()
        self.params = params
        self.progress_wrapper = progress_wrapper

    def run(self):
        try:
            # 在线程中执行耗时操作，通过包装器更新进度
            inclinedShaftDiagram(self.params, self.progress_wrapper)
            self.finished_success.emit()  # 任务成功完成
        except Exception as e:
            # 捕获异常并通过信号传递
            self.error_occurred.emit(getError2(2))


# 主类
class InclinedShaftWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = uic.loadUi(resource_path("static/ui/inclinedShaft.ui"), self)  # 加载主窗口的 UI 文件
        self.params = {
            # 输出文件
            "outfile": None,  # 文件名
            # 分层文件
            "fc": None,  # 文件名
            "fcx": None,  # 是否画线
            # 拉平文件
            "lp": None,  # 文件名
            "trange": None,  # 时间绘制范围
            "lpsd": None,  # 深度绘制范围，开始
            "lped": None,  # 文件名，结束
            "lpjx": None,  # 是否做负极性
            "lpagc": None,  # 是否做增益
            "lpgain": None,  # 振幅大小
            "stkw": None,  # 走廊时窗大小
            "stkdep": None,  # 走廊切除深度
            "timeskip": None,  # 深度轴刻度间隔
            "skip3": None,  # 时间轴刻度间隔
            "direction": None,  # 数据深度方向
            # 走廊文件
            "stk": None,  # 文件名
            "stkjx": None,  # 是否做负极性
            "stkagc": None,  # 是否做增益
            "stkgain": None,  # 振幅大小
            # 滤波走廊文件
            "stkbf": None,  # 文件名
            "stkbfjx": None,  # 是否做负极性
            "stkbfagc": None,  # 是否做增益
            "stkbfgain": None,  # 振幅大小
            "times": None,  # 时移
            # 地面文件
            "sei": None,  # 文件名
            "seijx": None,  # 是否做负极性
            "seiagc": None,  # 是否做增益
            "seigain": None,  # 振幅大小
            "seitimes": None,  # 时移
            "sein": None,  # 绘制道数
            # 岩性柱子
            "zhuzi": None,  # 文件名
            "zhuzidepmin": None,  # 柱子深度范围，开始
            "zhuzidepmax": None,  # 柱子深度范围，结束
            # 其他
            "kb": None,  # 补芯高
            "agc": None,  # 增益时窗
            "skip": None,  # 道间隔
            "skip2": None,  # 时间间隔
            # 设置
            "tpi": None,  # 拉平宽度
            "ips": None,  # 高度
            # "percentitle": None,  # percentitle
            "colour": None,  # rgb
            "opacity": None,  # opacity
            "lineweight": None,  # 绘制线宽
            "fontsize": None,  # 字体大小
            "angle": None,  # 旋转角度
        }  # 参数列表
        self.errMsgs = []  # 错误信息
        self.e_name = "inclinedShaft"  # 历史记录文件中的属性名
        self.module_name = "桥图|斜井"  # 模块名
        self.init_style()  # 初始化样式
        self.init_event()  # 初始化事件
        self.init_params()  # 初始化参数

    # ========================================================
    # 重写方法
    # ========================================================

    # 在 paintEvent 中绘制背景图片
    def paintEvent(self, event):
        painter = QPainter(self)
        pixmap = QPixmap(resource_path("static/image/bg2Cut.png"))
        painter.drawPixmap(self.rect(), pixmap)  # 使用 pixmap 填充整个窗口

    # 根据窗口宽度动态调整
    def resizeEvent(self, event):
        # 获取窗口当前宽度
        width = self.width()
        # 根据窗口宽度动态调整字体大小
        fontSize = int(width / 150)
        if fontSize < 10:
            fontSize = 10
        if fontSize > 18:
            fontSize = 18

        # 定义一个递归函数来遍历所有子控件，并设置字体大小
        def traverse_widgets(widget):
            if hasattr(widget, 'setFont'):
                font = widget.font()
                font.setPointSize(fontSize)
                widget.setFont(font)
            for child in widget.children():
                traverse_widgets(child)

        # 从主窗口开始遍历所有控件
        traverse_widgets(self)

        # 设置groupBox的内边距
        groupBoxes = self.findChildren(QGroupBox)
        for groupBox in groupBoxes:
            groupBox.setContentsMargins(fontSize, fontSize * 2, fontSize, fontSize)

        super().resizeEvent(event)

    # ========================================================
    # 初始化
    # ========================================================

    # 设置窗口图标和标题
    def init_style(self):
        self.ui.setWindowTitle("SeismicPlot-桥图|斜井")
        self.ui.setWindowIcon(QIcon(resource_path('static/image/favicon.ico')))
        self.resize(1200, 670)  # 设置窗口大小
        # 设置工具栏
        self.run_action = self.ui.toolBar.addAction(QtGui.QIcon(resource_path("static/image/run.png")), "运行")
        self.ui.toolBar.addSeparator()  # 分隔线
        self.reset_action = self.ui.toolBar.addAction(QtGui.QIcon(resource_path("static/image/reset.png")), "重置")
        self.ui.toolBar.addSeparator()
        self.view_image_action = self.ui.toolBar.addAction(QtGui.QIcon(resource_path("static/image/img.png")), "查看出图")
        self.ui.toolBar.addSeparator()
        self.history_action = self.ui.toolBar.addAction(QtGui.QIcon(resource_path("static/image/history.png")), "历史记录")
        self.ui.toolBar.addSeparator()
        self.setting_action = self.ui.toolBar.addAction(QtGui.QIcon(resource_path("static/image/setting.png")), "设置")
        self.ui.addToolBar(QtCore.Qt.ToolBarArea.LeftToolBarArea, self.ui.toolBar)

    # 给控件绑定事件
    def init_event(self):
        # 给文件选择按钮绑定事件
        self.ui.toolButton.clicked.connect(lambda: select_file(self.ui.lineEdit, "(*.png *.bmp)"))  # 输出文件
        self.ui.toolButton_2.clicked.connect(lambda: select_file(self.ui.lineEdit_2, "(*.xlsx *.xls)"))  # 分层文件
        self.ui.toolButton_3.clicked.connect(lambda: select_file(self.ui.lineEdit_3, "(*.sgy)"))  # 拉平文件
        self.ui.toolButton_4.clicked.connect(lambda: select_file(self.ui.lineEdit_11, "(*.sgy)"))  # 走廊文件
        self.ui.toolButton_5.clicked.connect(lambda: select_file(self.ui.lineEdit_13, "(*.sgy)"))  # 滤波走廊文件
        self.ui.toolButton_6.clicked.connect(lambda: select_file(self.ui.lineEdit_16, "(*.sgy)"))  # 镶嵌文件
        self.ui.toolButton_8.clicked.connect(lambda: select_file(self.ui.lineEdit_29, "(*.sgy)"))  # 镶嵌文件
        self.ui.toolButton_7.clicked.connect(lambda: select_file(self.ui.lineEdit_20, "(*.png *.bmp)"))  # 岩性柱子文件
        # 给工具栏按钮绑定事件
        self.run_action.triggered.connect(self.run)  # 运行
        self.reset_action.triggered.connect(self.init_params)  # 重置
        self.view_image_action.triggered.connect(lambda : show_image(self))  # 查看出图
        self.history_action.triggered.connect(lambda : get_history(self, historyInclinedShaft))  # 历史记录
        self.setting_action.triggered.connect(lambda : update_setting(self))  # 设置

    # 初始化参数
    def init_params(self):
        # 输出文件
        self.ui.lineEdit.setText("")  # 文件名
        # 分层文件
        self.ui.lineEdit_2.setText("")  # 文件名
        self.ui.radioButton_2.setChecked(True)  # 画线
        # 拉平文件
        self.ui.lineEdit_3.setText("")  # 文件名
        self.ui.lineEdit_6.setText("")  # 时间绘制范围-开始
        self.ui.lineEdit_4.setText("")  # 时间绘制范围-结束
        self.ui.lineEdit_8.setText("")  # 深度绘制范围-开始
        self.ui.lineEdit_5.setText("")  # 深度绘制范围-结束
        self.ui.radioButton_19.setChecked(True)  # 做负极性
        self.ui.radioButton_21.setChecked(True)  # 做增益
        self.ui.lineEdit_35.setText("")  # 振幅大小
        self.ui.lineEdit_36.setText("")  # 走廊时窗大小
        self.ui.lineEdit_7.setText("")  # 走廊切除深度
        self.ui.lineEdit_9.setText("300")  # 深度刻度间隔
        self.ui.lineEdit_10.setText("200")  # 时间刻度间隔
        self.ui.comboBox_2.setCurrentIndex(0)  # 深度方向
        # 走廊文件
        self.ui.lineEdit_11.setText("")  # 文件名
        self.ui.radioButton_8.setChecked(True)  # 做负极性
        self.ui.radioButton_9.setChecked(True)  # 做增益
        self.ui.lineEdit_12.setText("")  # 振幅大小
        # 滤波走廊文件
        self.ui.lineEdit_13.setText("")  # 文件名
        self.ui.radioButton_11.setChecked(True)  # 做负极性
        self.ui.radioButton_13.setChecked(True)  # 做增益
        self.ui.lineEdit_14.setText("")  # 振幅大小
        self.ui.lineEdit_15.setText("")  # 时移
        # 镶嵌文件
        self.ui.lineEdit_16.setText("")  # 文件名
        self.ui.radioButton_16.setChecked(True)  # 做负极性
        self.ui.radioButton_17.setChecked(True)  # 做增益
        self.ui.lineEdit_17.setText("")  # 振幅大小
        self.ui.lineEdit_18.setText("")  # 时移
        self.ui.lineEdit_19.setText("")  # 绘制道数
        # 地面文件
        self.ui.lineEdit_29.setText("")  # 文件名
        # 岩性柱子
        self.ui.lineEdit_20.setText("")  # 文件名
        self.ui.lineEdit_21.setText("")  # 柱子深度范围-开始
        self.ui.lineEdit_22.setText("")  # 柱子深度范围-结束
        # 其他
        self.ui.lineEdit_23.setText("")  # 补芯高
        self.ui.lineEdit_24.setText("500")  # 增益时窗
        self.ui.lineEdit_25.setText("1")  # 道间隔
        self.ui.lineEdit_26.setText("1")  # 时间间隔
        # 设置
        self.ui.lineEdit_27.setText("10")  # 拉平宽度
        self.ui.lineEdit_28.setText("11")  # 高度
        self.ui.lineEdit_30.setText("0")  # colour
        self.ui.lineEdit_37.setText("0")  # colour
        self.ui.lineEdit_38.setText("0")  # colour
        self.ui.lineEdit_31.setText("1")  # opacity
        self.ui.lineEdit_32.setText("0.2")  # lineweight
        self.ui.lineEdit_33.setText("30")  # fontsize
        self.ui.lineEdit_34.setText("90")  # 旋转角度

    # 从桥图|斜井历史记录页面historyInclinedShaft导入数据，重新加载桥图页面inclinedShaft的数据
    def load_params(self, obj):
        data = obj["data"]
        # 输出文件
        self.ui.lineEdit.setText(f"{data['outfile']}")  # 文件名
        # 分层文件
        self.ui.lineEdit_2.setText(f"{data['fc']}")  # 文件名
        if data['fcx'] == 1:  # 画线
            self.ui.radioButton_2.setChecked(True)
        else:
            self.ui.radioButton.setChecked(True)
        # 拉平文件
        self.ui.lineEdit_3.setText(f"{data['lp']}")  # 文件名
        self.ui.lineEdit_6.setText(f"{data['trange'][0]}")  # 时间绘制范围-开始
        self.ui.lineEdit_4.setText(f"{data['trange'][1]}")  # 时间绘制范围-结束
        self.ui.lineEdit_8.setText(f"{data['lpsd']}")  # 深度绘制范围-开始
        self.ui.lineEdit_5.setText(f"{data['lped']}")  # 深度绘制范围-结束
        if data['lpjx'] == 0:  # 做负极性
            self.ui.radioButton_19.setChecked(True)
        else:
            self.ui.radioButton_20.setChecked(True)
        if data['lpagc'] == 0:  # 做增益
            self.ui.radioButton_21.setChecked(True)
        else:
            self.ui.radioButton_22.setChecked(True)
        self.ui.lineEdit_35.setText(f"{data['lpgain']}")  # 振幅大小
        self.ui.lineEdit_36.setText(f"{data['stkw']}")  # 走廊时窗大小
        self.ui.lineEdit_7.setText(f"{data['stkdep']}")  # 走廊切除深度
        self.ui.lineEdit_9.setText(f"{data['timeskip']}")  # 深度刻度间隔
        self.ui.lineEdit_10.setText(f"{data['skip3']}")  # 时间刻度间隔
        self.ui.comboBox_2.setCurrentIndex(data['direction'])  # 深度方向
        # 走廊文件
        self.ui.lineEdit_11.setText(f"{data['stk']}")  # 文件名
        if data['stkjx'] == 0:  # 做负极性
            self.ui.radioButton_7.setChecked(True)  # 做负极性
        else:
            self.ui.radioButton_8.setChecked(True)  # 做负极性
        if data['stkagc'] == 0:  # 做增益
            self.ui.radioButton_9.setChecked(True)
        else:
            self.ui.radioButton_10.setChecked(True)
        self.ui.lineEdit_12.setText(f"{data['stkgain']}")  # 振幅大小
        # 滤波走廊文件
        self.ui.lineEdit_13.setText(f"{data['stkbf']}")  # 文件名
        if data['stkbfjx'] == 0:  # 做负极性
            self.ui.radioButton_11.setChecked(True)
        else:
            self.ui.radioButton_12.setChecked(True)
        if data['stkbfagc'] == 0:  # 做增益
            self.ui.radioButton_13.setChecked(True)
        else:
            self.ui.radioButton_14.setChecked(True)
        self.ui.lineEdit_14.setText(f"{data['stkbfgain']}")  # 振幅大小
        self.ui.lineEdit_15.setText(f"{data['times']}")  # 时移
        # 镶嵌文件
        self.ui.lineEdit_16.setText(f"{data['sei']}")  # 文件名
        if data['seijx'] == 0:  # 做负极性
            self.ui.radioButton_15.setChecked(True)
        else:
            self.ui.radioButton_16.setChecked(True)
        if data['seiagc'] == 0:  # 做增益
            self.ui.radioButton_17.setChecked(True)
        else:
            self.ui.radioButton_18.setChecked(True)
        self.ui.lineEdit_17.setText(f"{data['seigain']}")  # 振幅大小
        self.ui.lineEdit_18.setText(f"{data['seitimes']}")  # 时移
        self.ui.lineEdit_19.setText(f"{data['sein']}")  # 绘制道数
        # 地面文件
        self.ui.lineEdit_29.setText(f"{data.get('sei_origin', '')}")  # 文件名
        # 岩性柱子
        self.ui.lineEdit_20.setText(f"{data['zhuzi']}")  # 文件名
        self.ui.lineEdit_21.setText(f"{data['zhuzidepmin']}")  # 柱子深度范围-开始
        self.ui.lineEdit_22.setText(f"{data['zhuzidepmax']}")  # 柱子深度范围-结束
        # 其他
        self.ui.lineEdit_23.setText(f"{data['kb']}")  # 补芯高
        self.ui.lineEdit_24.setText(f"{data['agc']}")  # 增益时窗
        self.ui.lineEdit_25.setText(f"{data['skip']}")  # 道间隔
        self.ui.lineEdit_26.setText(f"{data['skip2']}")  # 时间间隔
        # 设置
        self.ui.lineEdit_27.setText(f"{data['tpi']}")  # 拉平宽度
        self.ui.lineEdit_28.setText(f"{data['ips']}")  # 高度
        self.ui.lineEdit_30.setText(f"{data['colour'][0]}")  # colour
        self.ui.lineEdit_37.setText(f"{data['colour'][1]}")  # colour
        self.ui.lineEdit_38.setText(f"{data['colour'][2]}")  # colour
        self.ui.lineEdit_31.setText(f"{data['opacity']}")  # opacity
        self.ui.lineEdit_32.setText(f"{data['lineweight']}")  # lineweight
        self.ui.lineEdit_33.setText(f"{data['fontsize']}")  # fontsize
        self.ui.lineEdit_34.setText(f"{data['angle']}")  # 旋转角度

        QTimer.singleShot(0, self.update)

    # ========================================================
    # 获取参数
    # ========================================================

    # 获取参数
    def get_params(self):
        self.errMsgs = []  # 重置错误信息
        # 输出文件
        self.params["outfile"] = self.get_file(self.ui.lineEdit, "输出文件|文件名")
        # 分层文件
        self.params["fc"] = self.get_file(self.ui.lineEdit_2, "分层文件|文件名")
        self.params["fcx"] = get_radio_value(self.ui.buttonGroup_9.checkedButton(), True)  # 是否画线
        # 拉平文件
        self.params["lp"] = self.get_file(self.ui.lineEdit_3, "拉平文件|文件名")
        self.params["trange"] = []  # 时间绘制范围
        self.params["trange"].append(self.get_line_edit_value(self.ui.lineEdit_6, "拉平文件|时间绘制范围（开始）"))
        self.params["trange"].append(self.get_line_edit_value(self.ui.lineEdit_4, "拉平文件|时间绘制范围（结束）"))
        self.params["lpsd"] = self.get_line_edit_value(self.ui.lineEdit_8, "拉平文件|深度绘制范围（开始）", "int")
        self.params["lped"] = self.get_line_edit_value(self.ui.lineEdit_5, "拉平文件|深度绘制范围（结束）", "int")
        self.params["lpjx"] = get_radio_value(self.ui.buttonGroup.checkedButton())  # 是否做负极性
        self.params["lpagc"] = get_radio_value(self.ui.buttonGroup_2.checkedButton())  # 是否做增益
        self.params["lpgain"] = self.get_line_edit_value(self.ui.lineEdit_35, "拉平文件|振幅大小")
        self.params["stkw"] = self.get_line_edit_value(self.ui.lineEdit_36, "拉平文件|走廊时窗大小", "int")
        self.params["stkdep"] = self.get_line_edit_value(self.ui.lineEdit_7, "拉平文件|走廊切除深度", "int")
        self.params["timeskip"] = self.get_line_edit_value(self.ui.lineEdit_9, "拉平文件|深度轴刻度间隔", "int")
        self.params["skip3"] = self.get_line_edit_value(self.ui.lineEdit_10, "拉平文件|时间轴刻度间隔", "int")
        self.params["direction"] = self.ui.comboBox_2.currentIndex()  # 数据深度方向
        # 走廊文件
        self.params["stk"] = self.get_file(self.ui.lineEdit_11, "走廊文件|文件名")
        self.params["stkjx"] = get_radio_value(self.ui.buttonGroup_3.checkedButton())  # 是否做负极性
        self.params["stkagc"] = get_radio_value(self.ui.buttonGroup_4.checkedButton())  # 是否做增益
        self.params["stkgain"] = self.get_line_edit_value(self.ui.lineEdit_12, "走廊文件|振幅大小")
        # 滤波走廊文件
        self.params["stkbf"] = self.get_file(self.ui.lineEdit_13, "滤波走廊文件|文件名")
        self.params["stkbfjx"] = get_radio_value(self.ui.buttonGroup_5.checkedButton())  # 是否做负极性
        self.params["stkbfagc"] = get_radio_value(self.ui.buttonGroup_6.checkedButton())  # 是否做增益
        self.params["stkbfgain"] = self.get_line_edit_value(self.ui.lineEdit_14, "滤波走廊文件|振幅大小")
        self.params["times"] = self.get_line_edit_value(self.ui.lineEdit_15, "滤波走廊文件|时移", "int")
        # 镶嵌文件
        self.params["sei"] = self.get_file(self.ui.lineEdit_16, "镶嵌文件|文件名")
        self.params["seijx"] = get_radio_value(self.ui.buttonGroup_7.checkedButton())  # 是否做负极性
        self.params["seiagc"] = get_radio_value(self.ui.buttonGroup_8.checkedButton())  # 是否做增益
        self.params["seigain"] = self.get_line_edit_value(self.ui.lineEdit_17, "地面文件|振幅大小")
        self.params["seitimes"] = self.get_line_edit_value(self.ui.lineEdit_18, "地面文件|时移", "int")
        self.params["sein"] = self.get_line_edit_value(self.ui.lineEdit_19, "地面文件|绘制道数", "int")
        # 地面文件
        self.params["sei_origin"] = self.get_file(self.ui.lineEdit_29, "地面文件|文件名")
        # 岩性柱子
        self.params["zhuzi"] = self.get_file(self.ui.lineEdit_20, "岩性柱子|文件名")
        self.params["zhuzidepmin"] = self.get_line_edit_value(self.ui.lineEdit_21, "岩性柱子|柱子深度范围（开始）", "int")
        self.params["zhuzidepmax"] = self.get_line_edit_value(self.ui.lineEdit_22, "岩性柱子|柱子深度范围（结束）", "int")
        # 其他
        self.params["kb"] = self.get_line_edit_value(self.ui.lineEdit_23, "其他|补芯高")
        self.params["agc"] = self.get_line_edit_value(self.ui.lineEdit_24, "其他|增益时窗", "int")
        self.params["skip"] = self.get_line_edit_value(self.ui.lineEdit_25, "其他|道间隔", "int")
        self.params["skip2"] = self.get_line_edit_value(self.ui.lineEdit_26, "其他|时间间隔", "int")
        # 设置
        self.params["tpi"] = self.get_line_edit_value(self.ui.lineEdit_27, "设置|深度比例尺", "int")
        self.params["ips"] = self.get_line_edit_value(self.ui.lineEdit_28, "设置|时间比例尺", "int")
        self.params["colour"] = []
        self.params["colour"].append(self.get_line_edit_value(self.ui.lineEdit_30, "设置|colour-r", "int"))
        self.params["colour"].append(self.get_line_edit_value(self.ui.lineEdit_37, "设置|colour-g", "int"))
        self.params["colour"].append(self.get_line_edit_value(self.ui.lineEdit_38, "设置|colour-b", "int"))
        self.params["opacity"] = self.get_line_edit_value(self.ui.lineEdit_31, "设置|opacity")
        self.params["lineweight"] = self.get_line_edit_value(self.ui.lineEdit_32, "设置|lineweight")
        self.params["fontsize"] = self.get_line_edit_value(self.ui.lineEdit_33, "设置|fontsize", "int")
        self.params["angle"] = self.get_line_edit_value(self.ui.lineEdit_34, "设置|旋转角度", "int")
        print(self.params)
        if len(self.errMsgs) != 0:
            QMessageBox.warning(self, self.errMsgs[0][0], self.errMsgs[0][1])
            return False
        return True

    # 获取数据输入框中的值，根据numType的值进行数据类型的转换
    def get_line_edit_value(self, lineEdit, msg, numType='float'):
        """
        获取数据输入框中的值，根据numType的值进行数据类型的转换

        Args:
            lineEdit (QlineEdit): QlineEdit对象
            msg (string): 错误弹窗提示信息
            numType (string): 目标数据类型，默认'float'

        Returns:


        Raises:


        Example:
            >>> add_numbers(self.ui.lineEdit_30, "其他|colour-r", "int")
        """
        text = lineEdit.text()
        if text:
            try:
                if numType == 'float':
                    return float(text)
                else:
                    return int(text)
            except ValueError:
                self.errMsgs.append(["输入错误", f"[{msg}]输入错误，请输入有效的数字！"])
        else:
            self.errMsgs.append(["输入错误", f"[{msg}]输入不能为空，请输入有效的数字！"])

    # 获取文件输入框中的值
    def get_file(self, lineEdit, msg):
        text = lineEdit.text()
        if text:
            return text
        else:
            self.errMsgs.append(["输入错误", f"[{msg}]不能为空，请输入正确的文件路径！"])


    # ========================================================
    # 运行
    # ========================================================

    # 运行，出图
    def run(self):
        if self.get_params():  # 获取参数，且当参数没有问题时调用
            try:
                # 在界面初始化部分修改如下
                self.ui.progressbar = Progress()  # 进度条
                self.ui.progressbar.show()

                # 创建线程安全的进度包装器并连接信号
                self.progress_wrapper = ProgressBarWrapper()
                self.progress_wrapper.update_progress.connect(self.ui.progressbar.start_progress)

                # 创建并启动工作线程
                self.worker_thread = WorkerThread(self.params, self.progress_wrapper)
                self.worker_thread.start()

                # 事件处理，当执行错误触发时，也会触发finished，所以改为finished_success
                # self.worker_thread.finished.connect(self.handle_thread_success)  # 完成时触发
                self.worker_thread.finished_success.connect(self.handle_thread_success)  # 执行成功时触发
                self.worker_thread.error_occurred.connect(self.handle_thread_error)  # 执行错误时触发
            except:
                # 这里只能捕获主线程初始化阶段的错误
                err = getError()
                QMessageBox.warning(self, f"{err['type']}",
                                    f"{err['msg']}, file in {err['file']}, line in {err['line']}.")


    # 运行错误处理函数
    def handle_thread_error(self, err):
        self.ui.progressbar.close()  # 关闭进度条，发生错误时需要手动关闭进度条
        QMessageBox.warning(self, f"{err['type']}",
                            f"{err['msg']}, file in {err['file']}, line in {err['line']}, \n {err['code']}.")
        # 保存历史记录
        setHistory(self, "error")

    # 运行成功处理函数
    def handle_thread_success(self):
        QMessageBox.information(self, 'SeismicPlot-桥图|斜井', '出图成功', QMessageBox.StandardButton.Ok)
        # 保存历史记录
        setHistory(self, "success")